package com.borko.healthcare.tapestry.pages;

import org.apache.tapestry5.PersistenceConstants;
import org.apache.tapestry5.ValidationException;
import org.apache.tapestry5.annotations.Persist;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.annotations.SetupRender;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.services.Cookies;
import org.springframework.context.ApplicationContext;

import com.borko.healthcare.entities.beans.MedicineBean;
import com.borko.healthcare.entities.interfaces.Medicine;
import com.borko.healthcare.entities.interfaces.Supplier;
import com.borko.healthcare.persistence.hibernate.services.MedicineManager;
import com.borko.healthcare.persistence.hibernate.services.SupplierManager;

public class AddMedicine {
	
	@Inject
	private Cookies cookies;
	
	@Property
	@Persist(PersistenceConstants.FLASH)
	private Medicine medicine;
	
	@Inject
	private ApplicationContext applicationContext;
	
	private SupplierManager supplierManager;
	private MedicineManager medicineManager;
	
	@SetupRender
	public void initilaize() {
		if (medicine == null) {
			medicine = new MedicineBean();
		}
	}
	
	public void onValidateFromMedicineForm() throws ValidationException {
		if (medicine.getDescription() == null
				|| medicine.getMilligrams() <= 0
				|| medicine.getName() == null
				|| medicine.getPrice() <= 0) {
			throw new ValidationException("Please fill all fields.");
		}
	}
	
	// TODO: redirect to view medicines page of supplier
	public void onSuccessFromMedicineForm() {
		medicineManager = (MedicineManager) applicationContext.getBean("medicineManager");
		supplierManager = (SupplierManager) applicationContext.getBean("supplierManager");
		
		int supplierId = Integer.parseInt(cookies.readCookieValue("userId"));
		Supplier supplier = supplierManager.getSupplier(supplierId);
		supplier.getMedicines().add(medicine);
		medicine.setSupplier(supplier);
		supplierManager.add(supplier);
		medicineManager.add(medicine);
	}

}
